
// 时间工具函数

import { startOfMonth, startOfDay, addDays, startOfYesterday, endOfYesterday, format, endOfWeek, startOfWeek, endOfDay } from 'date-fns';
// 时间段
const ranges = {
    t: [startOfDay(new Date()), endOfDay(new Date())], // '今天'
    y: [startOfYesterday(), endOfYesterday()], // '昨天'
    w: [startOfWeek(new Date()), endOfWeek(new Date())], // 本周
    m: [startOfMonth(new Date()), endOfDay(new Date())], // '本月'
    s: [startOfDay(addDays(new Date(), -6)), endOfDay(new Date())], // '7天'
    th: [startOfDay(addDays(new Date(), -29)), endOfDay(new Date())] // '30天'
};

/**
 * 获取指定时间段，常用于列表的时间搜索，与own-date-range-picker组件配合
 * @param mode 时间段类型 // t:今天 y:昨天 s:7天 th:30天 m:本月(开始时间为本月1号)
 * @param dateFormat 格式化 不传返回为Date类型，传了返回为string类型  常用：yyyy-MM-dd HH:mm:ss | yyyy-MM-dd
 * @returns {obj: {startTime, endTime}, arr: [startTime, endTime] } 返回两种类型，自由选择
 */
export const getDateRange = (dateFormat: string = 'yyyy-MM-dd HH:mm:ss', mode: 't' | 'y' | 'w' | 'm' | 's' | 'th' = 's') => {
    const date = ranges[mode];
    let startTime, endTime;
    if (dateFormat) {
        startTime = format(date[0], dateFormat);
        endTime = format(date[1], dateFormat);
    } else {
        startTime = date[0];
        endTime = date[1];
    }
    return {
        obj: { startTime, endTime },
        arr: [startTime, endTime]
    };
};

// 获取当前时间 20160106173721310
export const getJSCurrTime = () => {
    let s = '';
    const d = new Date();
    s += d.getFullYear();
    const month = d.getMonth() + 1;
    if (month < 10) {
        s += '0' + month;
    } else {
        s += month;
    }
    const day = d.getDate();
    if (day < 10) {
        s += '0' + day;
    } else {
        s += day;
    }
    const hour = d.getHours();
    if (hour < 10) {
        s += '0' + hour;
    } else {
        s += hour;
    }
    const minu = d.getMinutes();
    if (minu < 10) {
        s += '0' + minu;
    } else {
        s += minu;
    }
    const sec = d.getSeconds();
    if (sec < 10) {
        s += '0' + sec;
    } else {
        s += sec;
    }
    s += d.getMilliseconds();
    return s;
};

export const dateFormat = (_time: string, formatStr: string = 'yyyy-MM-dd HH:mm:ss') => {
    let time = _time ? new Date(_time) : new Date();
    return format(time, formatStr)
}